import 'package:flutter/material.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:rapid_kit/rapid_kit.dart';
import 'package:flutter/cupertino.dart';
import '../../theme.dart';
import '../../utils/lifecycle_aware.dart';
import '../../utils/snack_tips.dart';

/// 设备事件设置页面
class NotificationPage extends StatefulWidget {
  final String deviceId;

  const NotificationPage({super.key, required this.deviceId});

  @override
  State<NotificationPage> createState() => _NotificationPageState();
}

class _NotificationPageState extends LifecycleAwareState<NotificationPage> {
  RemotePushConfigure? _remotePushConfigure;
  LocalPushConfigure? _localPushConfigure;
  late String _deviceId;
  final _intervalSeconds = [60, 180, 300, 600, 1800];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildTitleBar(context),
      body: _buildRootBody(context),
    );
  }

  AppBar _buildTitleBar(BuildContext context) {
    return AppBar(
      leading: IconButton(
        icon: Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      automaticallyImplyLeading: false,
      backgroundColor: Colors.white,
      title: Text(
        "消息通知设置",
        style: TextStyle(
          fontSize: 17,
          fontFamily: "PingFang SC",
          fontWeight: FontWeight.w600,
        ),
      ),
      centerTitle: true,
    );
  }

  Widget _buildRootBody(BuildContext context) {
    final switchOn = _remotePushConfigure?.enable ?? false;
    return Container(
      padding: const EdgeInsets.all(16.0), // 添加内边距
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _buildNotificationSwitch(),
          const SizedBox(height: 10),

          if (switchOn)
            const Padding(
              padding: EdgeInsets.only(left: 16.0),
              child: Text("检查通知",style: TextStyle(color: Color(0xFFb2b2b2)),),
            ),
          const SizedBox(height: 10),
          if (switchOn) _pushCategories(),

          const SizedBox(height: 10),

          _notificationInterval(),
        ],
      ),
    );
  }

  Widget _pushCategories() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Color(0xFFf8f7f7), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      child: ListView.builder(
        shrinkWrap: true, // 让ListView自动调整高度
        physics: NeverScrollableScrollPhysics(), // 防止ListView滚动
        itemCount: _remotePushConfigure?.switcher?.length ?? 0,
        itemBuilder: (BuildContext context, int index) {
          return ListTile(
            contentPadding: EdgeInsets.fromLTRB(15, 0, 5, 0), // 调整左右边距
            title: Text(
              _remotePushConfigure?.switcher?[index].categoryName ?? '',
              style: _primaryTextStyle(),
            ),
            trailing: Transform.scale(
              scale: 0.8, // 缩小到0.8倍
              child: Switch(
                value: _remotePushConfigure?.switcher?[index].enable ?? false,
                activeTrackColor: SampleThemeConfigure.colorPrimary,
                onChanged: (bool newValue) async {
                  _remotePushConfigure?.switcher?[index].enable = newValue;
                  LogUtils.w("newValue${newValue}");
                  _localPushConfigure =
                      LocalPushConfigure.fromRemote(_remotePushConfigure!);
                  LogUtils.w("_localPushConfigure${_localPushConfigure}");
                  _updateNotificationSettings();
                },

              ),
            ),
          );
        },
      ),
    );
  }

  // SwitchListTile _notificationSwitch() {
  //   return SwitchListTile(
  //     title: Text(
  //       '报警消息推送',
  //       style: _primaryTextStyle(),
  //     ),
  //     subtitle: Text('检测到事件时，推送消息给手机', style: _secondaryTextStyle()),
  //     value: _remotePushConfigure?.enable ?? false,
  //     activeTrackColor: SampleThemeConfigure.colorPrimary,
  //     onChanged: (bool newValue) async {
  //       _localPushConfigure?.enable = newValue;
  //       _updateNotificationSettings();
  //     },
  //   );
  // }

  Widget _buildNotificationSwitch() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Color(0xFFf8f7f7), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 3, // 上边距
        bottom: 3, // 下边距
        left: 5, // 左边距
        right: 0, // 右边距
      ),
      child: Column(
        children: [
          InkWell(
            onTap: () {},
            child: Container(
              padding: EdgeInsets.only(
                top: 0,
                bottom: 0,
                left: 10,
                right: 5,
              ), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '所有通知',
                    style: _primaryTextStyle(),
                  ),
                  Transform.scale(
                    scale: 0.8, // 调整这个值来改变大小，0.8 表示缩小到原来的 80%
                    child: Switch(
                      value: _remotePushConfigure?.enable ?? false,
                      activeTrackColor: SampleThemeConfigure.colorPrimary,
                      onChanged: (bool newValue) async {
                        _localPushConfigure?.enable = newValue;
                        _updateNotificationSettings();
                      },
                    ),
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // Widget _notificationInterval() {
  //   final interval = _remotePushConfigure?.interval ?? 0;
  //   return ListTile(
  //     title: Text(
  //       '报警时间间隔',
  //       style: _primaryTextStyle(),
  //     ),
  //     subtitle: Text('报警较多可拉大间隔减少干扰', style: _secondaryTextStyle()),
  //     trailing: Row(
  //       mainAxisSize: MainAxisSize.min,
  //       children: [
  //         Text(
  //           (interval == 0 ? "未设置" : "${interval ~/ 60}分钟"),
  //           style: _secondaryTextStyle(),
  //         ),
  //         const SizedBox(width: 6),
  //         const Icon(Icons.arrow_forward_ios,
  //             size: 16, color: SampleThemeConfigure.colorTextHint),
  //       ],
  //     ),
  //     onTap: () => _onPickInterval(),
  //   );
  // }

  Widget _notificationInterval() {
    final interval = _remotePushConfigure?.interval ?? 0;
    return Container(
      decoration: BoxDecoration(
        color: Colors.white, // 设置白色背景
        borderRadius: BorderRadius.circular(12.0), // 设置圆角
        border: Border.all(
          color: Color(0xFFf8f7f7), // 设置边框颜色
          width: 1.0, // 设置边框宽度
        ),
        boxShadow: [
          BoxShadow(
            color: Color(0xFFf8f7f7), // 设置阴影颜色
            offset: Offset(0, 2), // 设置阴影偏移量
            blurRadius: 4.0, // 设置阴影模糊半径
            spreadRadius: 0.0, // 设置阴影扩散半径
          ),
        ],
      ),
      padding: EdgeInsets.only(
        top: 7, // 上边距
        bottom: 7, // 下边距
        left: 5, // 左边距
        right: 0, // 右边距
      ),
      child: Column(
        children: [
          InkWell(
            onTap: () => _onPickInterval(),
            child: Container(
              padding: EdgeInsets.only(
                top: 10,
                bottom: 10,
                left: 10,
                right: 10,
              ), // 设置内边距
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '报警时间间隔',
                    style: _primaryTextStyle(),
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        (interval == 0 ? "未设置" : "${interval ~/ 60}分钟"),
                        style: _secondaryTextStyle(),
                      ),
                      const SizedBox(width: 6),
                      const Icon(
                        Icons.arrow_forward_ios,
                        size: 16,
                        color: SampleThemeConfigure.colorTextHint,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _onPickInterval() {
    showModalBottomSheet(
      backgroundColor: Colors.white,
      context: context,
      builder: (BuildContext context) {
        return Padding(
          padding: const EdgeInsets.all(16.0), // 整体边界间距
          child: Wrap(
            children: _intervalSeconds.map((int interval) {
              return Container(
                margin: const EdgeInsets.only(bottom: 16.0),
                child: ListTile(
                  title: Text("${interval ~/ 60}分钟"),
                  onTap: () async {
                    _localPushConfigure?.interval = interval;
                    _updateNotificationSettings();
                    Navigator.pop(context);
                  },
                ),
              );
            }).toList(),
          ),
        );
      },
    );
  }

  TextStyle _secondaryTextStyle() =>
      const TextStyle(fontSize: 14.0, color: Color.fromRGBO(125, 123, 123, 1));

  TextStyle _primaryTextStyle() =>
      const TextStyle(
          fontSize: 16.0,
          color: SampleThemeConfigure.colorTextPrimary,
          fontWeight: FontWeight.bold);

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId;
    _loadNotificationSettings();
  }

  void _updateNotificationSettings() async {
    LogUtils.w("_localPushConfigure${_localPushConfigure}");
    if (_localPushConfigure == null) return;
    final resp = await EventService.updateNotificationSettings(
        _deviceId, _localPushConfigure!);
    if (!mounted) return;
    if (!resp.success) {
      SnackTips.show(context, "Faild: ${resp.message}");
    }

    _loadNotificationSettings();
  }

  void _loadNotificationSettings() async {
    final resp = await EventService.currentNotificationSettings(_deviceId);
    if (!mounted) return;
    if (resp.success) {
      _localPushConfigure = LocalPushConfigure.fromRemote(resp.data!);
      setState(() {
        _remotePushConfigure = resp.data;
      });
    } else {
      SnackTips.show(context, "Faild: ${resp.message}");
    }
  }
}
